package com.mysteel.gateway.config;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.fastjson.JSON;
import com.mysteel.common.exception.BizCodeEnum;
import com.mysteel.common.utils.R;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * ProjectName: mail
 * ClassName: SentinelGatewayConfig
 * Description:
 * date: 2021/04/20/020 11:25
 *
 * @author xiaochao
 */
@Configuration
public class SentinelGatewayConfig {

    public SentinelGatewayConfig() {
        GatewayCallbackManager.setBlockHandler(new BlockRequestHandler() {
            /**
             * 网关限流了就会回调
             * @param serverWebExchange
             * @param throwable
             * @return
             */
            @Override
            public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
                R error = R.error(BizCodeEnum.REQUEST_BLOCK_EXCEPTION.getCode(), BizCodeEnum.REQUEST_BLOCK_EXCEPTION.getMsg());
                return ServerResponse.ok().body(Mono.just(JSON.toJSON(error)), String.class);
            }
        });
    }
}
